/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.neo.web.jsf.beans.admin.users;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.com.greensoft.neo.dao.DaoException;
import ar.com.greensoft.neo.dao.GroupDao;
import ar.com.greensoft.neo.dao.UserDao;
import ar.com.greensoft.neo.model.Authority;
import ar.com.greensoft.neo.model.Group;
import ar.com.greensoft.neo.model.GroupMember;
import ar.com.greensoft.neo.model.User;
import ar.com.greensoft.neo.util.ApplicationRoles;
import ar.com.greensoft.neo.web.jsf.beans.common.CommonViewBean;
import ar.com.greensoft.neo.web.jsf.util.JSFMenuUtil;

/**
 * @author Jorge E. Villaverde
 *
 */
@Component
@RequestScoped
@ManagedBean
public class EditUserBean extends CommonViewBean {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private GroupDao groupDao;
	
	/**
	 * Editing User
	 */
	private User user;
	
	/**
	 * Available Authorities
	 */
	private List<String> authorities;
	/**
	 * User authorities
	 */
	private List<String> selectedAuthorities;
	
	private List<Group> groups;
	
	private List<Group> selectedGroups;

	
	@PostConstruct  
	public void init() { 
		authorities = new ArrayList<String>();
		for(ApplicationRoles role : ApplicationRoles.values())
			authorities.add(role.name());
		
		clearData();  
	} 
	
	public void clearData() {
		if(user == null){
			this.selectedAuthorities = null;
			this.selectedGroups = null;
			try {
				groups = groupDao.findAll();
			} catch (DaoException e) {
			}
		}else{
			this.selectedAuthorities = new ArrayList<String>();
			for(Authority auth : user.getAuthorities()){
				selectedAuthorities.add(auth.getAuthority());
			}
			this.selectedGroups = new ArrayList<Group>();
			for(GroupMember gm : user.getGroups()){
				selectedGroups.add(gm.getGroup());
			}
		}
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String showEdit(){
		if(this.user == null)
			throw new IllegalStateException("user not set");

		FacesContext ctx = FacesContext.getCurrentInstance();
		cancelView = ctx.getViewRoot().getViewId();
		
		selectedAuthorities = new ArrayList<String>();
		
		for(Authority authority : user.getAuthorities()){
			selectedAuthorities.add(authority.getAuthority());
		}
		
		return JSFMenuUtil.buildMenuPath(ADMIN_PATH, "users", EDIT_ACTION);
	}

	public String editUser(){
		if(this.user == null)
			throw new IllegalStateException("user not set");
		
		if(logger.isTraceEnabled())
			logger.trace("Saving User: " + user.getUsername());
		
		try {
			userDao.merge(user);
			// Revoke all Authorities
			for(Authority authority : user.getAuthorities()){
				userDao.removeAuthority(user, authority.getAuthority());
			}
			// Grant Selected
			for(String authorityName : selectedAuthorities){
				Authority authority = new Authority();
				authority.setUser(user);
				authority.setAuthority(authorityName);
				userDao.addAuthority(authority);
			}
		} catch (DaoException e) {
			logger.error(e.getMessage());
		}
		
		if(logger.isTraceEnabled())
			logger.trace("User " + user.getUsername() + " SAVED.");
		
		if(persistReturnView != null && !persistReturnView.isEmpty())
			return persistReturnView + JSFMenuUtil.JSF_REDIRECT;
		return showEdit();		
	}
	
	public List<String> getAuthorities() {
		return authorities;
	}

	public void setAuthorities(List<String> authorities) {
		this.authorities = authorities;
	}

	public List<String> getSelectedAuthorities() {
		return selectedAuthorities;
	}

	public void setSelectedAuthorities(List<String> selectedAuthorities) {
		this.selectedAuthorities = selectedAuthorities;
	}

	@Override
	protected String menuRole() {
		return ADMIN_PATH;
	}

	@Override
	protected String menuName() {
		return "users";
	}

	public List<Group> getGroups() {
		return groups;
	}

	public void setGroups(List<Group> groups) {
		this.groups = groups;
	}

	public List<Group> getSelectedGroups() {
		return selectedGroups;
	}

	public void setSelectedGroups(List<Group> selectedGroups) {
		this.selectedGroups = selectedGroups;
	}	
}
